package com.sqs.controller;

import com.sqs.dto.ChatDTO;
import com.sqs.service.IChatMessageService;
import com.sqs.vo.ChatVO;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import reactor.core.scheduler.Schedulers;

@Controller
public class ChatController {

    @Autowired
    private IChatMessageService iChatMessageService;
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    /**
     * 接收前端发送到 /web/chat 的消息
     */
    @MessageMapping("/chat")
    public void handleChat(ChatDTO chatDTO) {
        Long sessionId = chatDTO.getSessionId();
        String userMessage = chatDTO.getContent();

        // 调用 AI 流式接口，异步推送每个片段
        iChatMessageService.streamChat(sessionId, userMessage)
                // 在弹性线程池执行，避免阻塞消息处理线程
                .publishOn(Schedulers.boundedElastic())
                .subscribe(
                        chunk -> {
                            // 每个片段到达时，推给前端
                            messagingTemplate.convertAndSend("/topic/reply/" + sessionId,
                                    new ChatVO(chunk, "chunk"));
                        },
                        error -> {
                            // 出错时通知前端
                            messagingTemplate.convertAndSend("/topic/reply/" + sessionId,
                                    new ChatVO("服务错误: " + error.getMessage(), "error"));
                        },
                        () -> {
                            // 完成时通知前端（可用于前端结束拼接）
                            messagingTemplate.convertAndSend("/topic/reply/" + sessionId,
                                    new ChatVO("", "end"));
                        }
                );
    }

}
